package cn.openea.perpartner.crm.web.controller;


import cn.openea.perpartner.common.core.constant.UserConstants;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.crm.util.UserContext;
import cn.openea.perpartner.crm.web.entity.CrmRole;
import cn.openea.perpartner.crm.web.service.ICrmRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色信息表(CrmRole)表控制层
 *
 * @author Weird077
 * @since 2022-12-19 22:30:36
 */
@Api("角色信息")
@RestController
@RequestMapping("crm/role")
public class CrmRoleController extends BaseController {

    @Autowired
    private ICrmRoleService roleService;

    @ApiOperation("角色列表")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody CrmRole role) {
        startPage();
        List<CrmRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }
    @ApiOperation("角色信息")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }
    @PostMapping("/add")
    public AjaxResult add(@RequestBody CrmRole role)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateUser(UserContext.getUserId());
        role.setUpdateUser(UserContext.getUserId());
        return toAjax(roleService.insertRole(role));

    }
    @PostMapping("/edit")
    public AjaxResult edit( @RequestBody CrmRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateUser(UserContext.getUserId());
        if (roleService.updateRole(role))
        {
            return success();
        }
        return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }
}

